<template>
  <div class="edit-page-wrap">
    <Head title="运营商信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="90px"
          class="edit-form-wrap"
        >
          <el-form-item label="方案名称" prop="name">
            <el-input
              v-model.trim="ruleForm.name"
              placeholder="请输入方案名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="活动电站" prop="stationType" class="has-tips">
            <el-radio-group
              v-model="ruleForm.stationType"
              v-for="(item, index) in optionsS.stationType"
              :key="index"
              @change="handleStationType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              {{
                ruleForm.stationType === '0'
                  ? '所有电站均参与活动'
                  : ruleForm.stationType === '1'
                  ? '选定运营商后，该运营商所有的电站均参与活动，含活动期间新增的电站'
                  : '选定单电站后，仅所选电站参与活动，活动期间运营商新增电站不在活动范围内'
              }}
            </div>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.stationType === '1'"
            label=""
            prop="treeOrgs"
          >
            <QcTree
              ref="treeOrgRef"
              :setCheckedKeys="ruleForm.treeOrgs"
              :data="optionsS.org"
              :showCheckbox="true"
              :checkStrictly="true"
              @handleCheck="handleCheckOrg"
            ></QcTree>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.stationType === '2'"
            label=""
            prop="treeStations"
          >
            <QcTree
              ref="treeStationRef"
              :setCheckedKeys="ruleForm.treeStations.split(',')"
              :data="optionsS.station"
              :showCheckbox="true"
              @handleCheck="handleCheckStation"
            ></QcTree>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="方案配置">
      <template #content>
        <el-form
          ref="ruleFormRef1"
          :model="ruleForm"
          :rules="rules"
          label-width="90px"
          class="edit-form-wrap"
        >
          <el-form-item label="活动时间" prop="times">
            <div class="edit-date-wrap">
              <el-date-picker
                v-model="ruleForm.times"
                popper-class="qc-date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                :disabled-date="disabledDate"
                @change="handleChangeTimes"
              />
            </div>
          </el-form-item>
          <el-form-item label="活动周天" prop="weeks">
            <el-checkbox-group
              v-model="ruleForm.weeks"
              @change="handleChangeWeek"
            >
              <el-checkbox
                v-for="item in optionsS.week"
                :key="item.value"
                :label="item.label"
                :disabled="item.disabled"
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="活动介绍" prop="introduce">
            <el-input
              v-model.trim="ruleForm.introduce"
              placeholder="请输入活动介绍"
              maxlength="200"
              type="textarea"
              :rows="3"
              show-word-limit
              clearable
            />
          </el-form-item>
          <div class="time-wrap">
            <el-form-item label="电费优惠" prop="powerPromotionalType">
              <qc-select
                :value="ruleForm.powerPromotionalType"
                :options="optionsS.promotionalType"
                placeholder="请选择优惠类型"
                @change="handleChangePower"
              >
              </qc-select>
            </el-form-item>
            <el-form-item
              v-if="ruleForm.powerPromotionalType === '0'"
              label=""
              prop="powerPromotionalAmount"
              label-width="12px"
            >
              <el-input
                v-model.trim="ruleForm.powerPromotionalAmount"
                placeholder="精确4位小数"
                maxlength="10"
                clearable
              >
                <template #append>元/度</template>
              </el-input>
            </el-form-item>
            <el-form-item
              v-else-if="ruleForm.powerPromotionalType === '1'"
              label=""
              prop="powerPromotionalRatio"
              label-width="12px"
            >
              <el-input
                v-model.trim="ruleForm.powerPromotionalRatio"
                placeholder="精确整数"
                maxlength="10"
                clearable
              >
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item v-else label="" label-width="12px">
              <el-input
                :v-model="''"
                placeholder=""
                maxlength="10"
                clearable
                disabled
              />
            </el-form-item>
          </div>
          <div class="time-wrap">
            <el-form-item label="服务费优惠" prop="servicePromotionalType">
              <qc-select
                :value="ruleForm.servicePromotionalType"
                :options="optionsS.promotionalType"
                placeholder="请选择优惠类型"
                @change="handleChangeService"
              >
              </qc-select>
            </el-form-item>
            <el-form-item
              v-if="ruleForm.servicePromotionalType === '0'"
              label=""
              prop="servicePromotionalAmount"
              label-width="12px"
            >
              <el-input
                v-model.trim="ruleForm.servicePromotionalAmount"
                placeholder="精确4位小数"
                maxlength="10"
                clearable
              >
                <template #append>元/度</template>
              </el-input>
            </el-form-item>
            <el-form-item
              v-else-if="ruleForm.servicePromotionalType === '1'"
              label=""
              prop="servicePromotionalRatio"
              label-width="12px"
            >
              <el-input
                v-model.trim="ruleForm.servicePromotionalRatio"
                placeholder="精确整数"
                maxlength="10"
                clearable
              >
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item v-else label="" label-width="12px">
              <el-input
                :v-model="''"
                placeholder=""
                maxlength="10"
                clearable
                disabled
              />
            </el-form-item>
          </div>
          <el-form-item label="活动用户" prop="targetType" class="has-tips">
            <el-radio-group
              v-model="ruleForm.targetType"
              v-for="(item, index) in optionsS.targetType"
              :key="index"
              @change="handleTargetType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              {{
                ruleForm.targetType === '0'
                  ? '所有用户均可参与活动'
                  : ruleForm.targetType === '1'
                  ? '选定企业后，该企业所有用户均可参与活动，含活动期间新增的用户'
                  : '选定标签后，该标签内所有均可参与活动，标签用户添加、删除会同步更新'
              }}
            </div>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.targetType === '1'"
            label=""
            prop="treeVehicles"
          >
            <QcTree
              ref="treeVehiclesRef"
              :setCheckedKeys="ruleForm.treeVehicles"
              :data="optionsS.vehicle"
              :showCheckbox="true"
              :checkStrictly="true"
              @handleCheck="handleCheckVehicles"
            ></QcTree>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.targetType === '2'"
            label=""
            prop="treeLabels"
          >
            <QcTree
              ref="treeLabelRef"
              :setCheckedKeys="ruleForm.treeLabels.split(',')"
              :data="optionsS.label"
              :showCheckbox="true"
              @handleCheck="handleCheckLabel"
            ></QcTree>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Head from '@/components/head/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import { queryDicByParent } from '@/service/apis/api';
import {
  stationActivitySave,
  stationActivityUpdate,
  stationActivityDetail,
} from '@/service/apis/market';
import {
  stationTreeDataByChannel,
  queryCarList,
  queryVehicle,
  queryLabelListByName,
} from '@/service/apis/org';
import { FormInstance, FormRules } from 'element-plus';
import { WEEK } from '@/utils/dictionaries';
import { getWeek } from '@/utils/utils';
import { IS_DECIMAL_4, IS_INT_0 } from '@/utils/verify';
import { cloneDeep } from 'lodash';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();
const ruleFormRef1 = ref<FormInstance>();
const treeOrgRef = ref();
const treeVehiclesRef = ref();

const optionsS = reactive({
  stationType: [] as any,
  targetType: [] as any,
  org: [] as any,
  station: [] as any,
  vehicle: [] as any,
  label: [] as any,
  promotionalType: [] as any,
  week: cloneDeep(WEEK) as any,
});

const orgId = window.localStorage.getItem('orgId') || '';
queryDicByParent({
  listDtos: [
    'stationTargetType',
    'stationActivityTargetType',
    'promotionalType',
  ],
}).then((res: any) => {
  if (res) {
    if (orgId) {
      optionsS.stationType = res.stationTargetType.filter(
        (item: any) => item.value !== '0'
      );
      ruleForm.stationType = '1';
      optionsS.targetType = res.stationActivityTargetType.filter(
        (item: any) => item.value !== '0'
      );
      ruleForm.targetType = '1';
    } else {
      optionsS.stationType = res.stationTargetType;
      optionsS.targetType = res.stationActivityTargetType;
    }
    optionsS.promotionalType = res.promotionalType;
  }
});

// 获取电站运营商树
const getOrgs = () => {
  queryCarList({}).then((res: any) => {
    if (res) {
      optionsS.org = res;
    }
  });
};

// 获取电站树
const getStations = () => {
  stationTreeDataByChannel({ cecType: 2 }).then((res: any) => {
    if (res) {
      optionsS.station = res;
    }
  });
};

// 获取车辆机构
const getVehicle = () => {
  queryVehicle({}).then((res: any) => {
    if (res) {
      optionsS.vehicle = res;
    }
  });
};

// 获取标签
const getLabel = () => {
  queryLabelListByName({}).then((res: any) => {
    if (res) {
      optionsS.label = res.listMap;
    }
  });
};

const disabledDate = (time: any) => {
  return time.getTime() < new Date(new Date().toLocaleDateString()).getTime();
};

const ruleForm: any = reactive({
  id: '',
  name: '', // 方案名称
  stationType: '0', //活动电站
  stationIds: '', //电站类型ids
  treeOrgs: [] as any, //限制站点数据-运营商-树
  treeStations: '', //限制站点数据-电站树
  startTime: '', // 活动时间-开始时间
  endTime: '', // 活动时间-结束时间
  times: [] as any, //活动时间-组件
  week: '', //活动周天
  weeks: [] as any, //活动周天-组件
  introduce: '', //活动介绍
  powerPromotionalType: undefined as any, //电费优惠-类型
  powerPromotionalAmount: '', //电费优惠-价格
  powerPromotionalRatio: '', //电费优惠-比例
  servicePromotionalType: undefined as any, //服务费优惠-类型
  servicePromotionalAmount: '', //服务费优惠-价格
  servicePromotionalRatio: '', //服务费优惠-比例
  targetType: '0', //活动用户
  targetIds: '', //活动用户ids
  treeVehicles: [] as any, //活动用户-机构树
  treeLabels: '', //活动用户-标签树
});

const checkTreeOrg = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeOrgRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (arr.length === 0) {
    callback(new Error('请选择具体的电站运营商'));
  }
  callback();
};
const checkTreeVehicles = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeVehiclesRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (arr.length === 0) {
    callback(new Error('请选择具体的用户企业（车辆机构）'));
  }
  callback();
};
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入方案名称', trigger: 'blur' }],
  stationType: [
    { required: true, message: '请选择活动电站', trigger: ['blur', 'change'] },
  ],
  treeOrgs: [
    { required: true, message: '请选择运营商', trigger: ['blur', 'change'] },
    { validator: checkTreeOrg, trigger: ['blur', 'change'] },
  ],
  treeStations: [
    { required: true, message: '请选择电站', trigger: ['blur', 'change'] },
  ],
  times: [
    { required: true, message: '请选择活动时间', trigger: ['blur', 'change'] },
  ],
  weeks: [
    { required: true, message: '请选择活动周天', trigger: ['blur', 'change'] },
  ],
  introduce: [{ required: true, message: '请输入活动介绍', trigger: 'blur' }],
  powerPromotionalType: [
    { required: true, message: '请选择优惠类型', trigger: ['blur', 'change'] },
  ],
  powerPromotionalAmount: [
    { required: true, message: '请输入优惠价格', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_4,
      message: '精确到4位小数',
      trigger: 'blur',
    },
  ],
  powerPromotionalRatio: [
    { required: true, message: '请输入优惠折扣', trigger: 'blur' },
    {
      pattern: IS_INT_0,
      message: '精确到整数',
      trigger: 'blur',
    },
  ],
  servicePromotionalType: [
    { required: true, message: '请选择优惠类型', trigger: ['blur', 'change'] },
  ],
  servicePromotionalAmount: [
    { required: true, message: '请输入优惠价格', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_4,
      message: '精确到4位小数',
      trigger: 'blur',
    },
  ],
  servicePromotionalRatio: [
    { required: true, message: '请输入优惠折扣', trigger: 'blur' },
    {
      pattern: IS_INT_0,
      message: '精确到整数',
      trigger: 'blur',
    },
  ],
  targetType: [
    { required: true, message: '请选择活动用户', trigger: ['blur', 'change'] },
  ],
  treeVehicles: [
    { required: true, message: '请选择企业', trigger: ['blur', 'change'] },
    { validator: checkTreeVehicles, trigger: ['blur', 'change'] },
  ],
  treeLabels: [
    { required: true, message: '请选择标签', trigger: ['blur', 'change'] },
  ],
});

const handleStationType = (val: any) => {
  if (val === '1' && optionsS.org.length === 0) {
    getOrgs();
  } else if (val === '2' && optionsS.station.length === 0) {
    getStations();
  }
};

const handleTargetType = (val: any) => {
  if (val === '1' && optionsS.vehicle.length === 0) {
    getVehicle();
  } else if (val === '2' && optionsS.label.length === 0) {
    getLabel();
  }
};
const handleChangeWeek = (e: any) => {
  ruleForm.week = e;
};

const handleChangePower = (e: any) => {
  ruleForm.powerPromotionalType = e;
};

const handleChangeService = (e: any) => {
  ruleForm.servicePromotionalType = e;
};

const handleChangeTimes = (e: any) => {
  if (e?.length === 2) {
    optionsS.week = getWeek(e, WEEK);
  } else {
    optionsS.week = cloneDeep(WEEK);
  }
  ruleForm.weeks = [];
};

const handleCheckOrg = (data: any, checkedData: any, checkedChildData: any) => {
  ruleForm.treeOrgs = checkedChildData;
};
const handleCheckStation = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.treeStations = checkedChildData.toString();
};
const handleCheckVehicles = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.treeVehicles = checkedChildData;
};
const handleCheckLabel = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.treeLabels = checkedChildData.toString();
};

if (id) {
  stationActivityDetail(id).then((res: any) => {
    if (res) {
      for (const key in ruleForm) {
        if (res[key]) {
          ruleForm[key] = res[key];
        }
      }
      ruleForm.stationType = String(res.stationType);
      ruleForm.targetType = String(res.targetType);
      ruleForm.powerPromotionalType = String(res.powerPromotionalType);
      ruleForm.servicePromotionalType = String(res.servicePromotionalType);
      //活动日期
      ruleForm.times = [res.startTime, res.endTime];
      // 活动周天
      const arr = [] as any;
      WEEK.forEach((item: any) => {
        if (res.week.includes(item.value)) {
          arr.push(item.label);
        }
      });
      ruleForm.weeks = arr;
      optionsS.week = getWeek(ruleForm.times, WEEK);
      //电站树
      if (ruleForm.stationType === '2') {
        ruleForm.treeStations = res.stationIds;
        getStations();
      } else if (ruleForm.stationType === '1') {
        ruleForm.treeOrgs = res.stationIds.split(',');
        getOrgs();
      }
      // 用户树
      if (ruleForm.targetType === '1') {
        ruleForm.treeVehicles = res.targetIds.split(',');
        getVehicle();
      } else if (ruleForm.targetType === '2') {
        ruleForm.treeLabels = res.targetIds;
        getLabel();
      }
    }
  });
} else {
  nextTick(() => {
    ruleForm.powerPromotionalType = undefined as any;
    ruleForm.servicePromotionalType = undefined as any;
    const timer = setTimeout(() => {
      ruleFormRef1.value?.clearValidate([
        'powerPromotionalType',
        'servicePromotionalType',
      ]);
      clearTimeout(timer);
    });
  });
  if (orgId) {
    getOrgs();
    getVehicle();
  }
}

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value || !ruleFormRef1.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleFormRef1.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        ruleFormRef1.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  // 活动时间
  ruleForm.startTime = ruleForm.times[0];
  ruleForm.endTime = ruleForm.times[1];
  // 周期
  const arr = [] as any;
  const str = ruleForm.weeks.toString();
  WEEK.forEach((item: any) => {
    if (str.includes(item.label)) {
      arr.push(item.value);
    }
  });
  ruleForm.week = arr.toString();
  // 电站树
  ruleForm.stationIds = '';
  if (ruleForm.stationType === '1') {
    const arr: any = [];
    const treeOrg = treeOrgRef.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        arr.push(item.id);
      }
    });
    ruleForm.stationIds = arr.toString();
  } else if (ruleForm.stationType === '2') {
    ruleForm.stationIds = ruleForm.treeStations;
  }
  // ruleForm.stationIds =
  //   ruleForm.stationType === '1'
  //     ? ruleForm.treeOrgs
  //     : ruleForm.stationType === '2'
  //     ? ruleForm.treeStations
  //     : '';
  // 用户数
  ruleForm.targetIds = '';
  if (ruleForm.targetType === '1') {
    const arr: any = [];
    const treeOrg = treeVehiclesRef.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        arr.push(item.id);
      }
    });
    ruleForm.targetIds = arr.toString();
  } else if (ruleForm.targetType === '2') {
    ruleForm.targetIds = ruleForm.treeLabels;
  }
  // ruleForm.targetIds =
  //   ruleForm.targetType === '1'
  //     ? ruleForm.treeVehicles
  //     : ruleForm.targetType === '2'
  //     ? ruleForm.treeLabels
  //     : '';
  console.log('rr----', ruleForm);
  if (id) {
    stationActivityUpdate(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    stationActivitySave(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>

<style lang="scss" scoped>
.time-wrap {
  display: flex;
  :deep(.el-input),
  :deep(.el-select-v2) {
    width: 144px !important;
  }
  :deep(.el-form-item:last-child .el-form-item__content) {
    padding-left: 0;
    .el-form-item__error {
      padding-left: 0;
    }
  }
}
</style>